/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.annotation.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.balisunrise.annotation.VisualEntity;
import org.balisunrise.annotation.Filter;

/**
 * Esta classe contém os atributos para construção de um filtro de uma entidade.
 *
 * @author Glauco
 */
public class FilterUtilities extends VisualEntityUtilities{

    private static final String MESSAGE = "Erro ao ler Annotation \"Filter\".";
    
    /**
     * Quantidade de atributos utilizados no filtro.
     */
    public int length;

    /**
     * Lista dos Filtros.
     */
    public List<CriteriaUtilities> filters;

    /**
     * Cria novo FilterUtilities
     */
    public FilterUtilities(){
        filters = new ArrayList<CriteriaUtilities>();
    }

    /**
     * Lê a annotation Filter com o alias da VisualEntity.
     * @param entityClass Classe para ler.
     * @param alias alias da Filter.
     * @return a annotation Filter do alias.
     * @throws AnnotationsUtilitiesException Caso não encontre.
     */
    public static Filter readFilterAnnotation(Class entityClass, String alias)
            throws AnnotationsUtilitiesException{

        if (entityClass == null)
            throw new AnnotationsUtilitiesException( MESSAGE +
                    "\nParâmentro \"entityClass\" não pode ser nulo!");

        if (alias == null)
            throw new AnnotationsUtilitiesException( MESSAGE +
                    "\nParâmentro \"alias\" não pode ser nulo!");

        VisualEntity ve = readVisualEntityAnnotation(entityClass);
        for (int i = 0; i < ve.filters().length; i++) {
            Filter filter = ve.filters()[i];
            for (int j = 0; j < filter.alias().length; j++) {
                if (filter.alias()[j].equals(alias))
                    return filter;
            }
        }

        throw new AnnotationsUtilitiesException( MESSAGE +
                "\nAnnotation \"Filter\" não encontrada para o " +
                "nome\""+ alias +"\"!");
    }

    /**
     * Le a annotation Filter e cria um FilterUtilities a parir dos dados da
     * annotation.
     *
     * @param entityClass Classe para ler.
     * @param alias alias da Filter.
     * @return FilterUtilities
     * @throws AnnotationsUtilitiesException Caso não encontre a annotation ou
     * algum parâmetro seja nulo.
     */
    public static FilterUtilities create(Class entityClass, String alias)
            throws AnnotationsUtilitiesException{

        if (entityClass == null)
            throw new AnnotationsUtilitiesException( MESSAGE +
                    "\nParâmentro \"entityClass\" não pode ser nulo!");

        if (alias == null)
            throw new AnnotationsUtilitiesException( MESSAGE +
                    "\nParâmentro \"alias\" não pode ser nulo!");

        // Le a anotação Filter
        Filter f = readFilterAnnotation(entityClass, alias);

        FilterUtilities fu = new FilterUtilities();
        fu.entityClass = entityClass;
        fu.alias = alias;
        fu.title = f.title();

        // para cada campo da classe, cria os filtros.
        ReflectUtilities ru = new ReflectUtilities(entityClass);
        for (Field field : ru.getDeclaredFields()) {
            try{
                fu.filters.add(CriteriaUtilities.create(field, alias));
            }catch(AnnotationsUtilitiesException aue){
                continue;
            }
        }

        //ordena os filtros
        CriteriaUtilities.sortFilterFieldsList(fu.filters);

        // verifica os filtros embedded e selection
        for (CriteriaUtilities fcu : fu.filters) {
            if (fcu.type != CriteriaUtilities.DEFINITION){
                FilterUtilities fuAux = create(fcu.field.getType(), fcu.call);
                fcu.embedded = fuAux.filters;
            }
        }

        // conta número de filtros
        fu.length = 0;
        for (CriteriaUtilities fcu : fu.filters) {
            fu.length += fcu.count();
        }
        return fu;
    }
}
